// pages/addAddr/addAddr.js
var common = require("../../utils/Conmon.js");

var provinceId = 0; //省ID
var province = ''; //省昵称
var cityId = 0; //市ID
var city = ''; //市昵称
var districtId = 0; //区或县ID
var district = ''; //区或县昵称
var citys = []; //本地保存市对象数组
var districts = []; //本地保存区对象数组
var appData = getApp().globalData;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    From: '',
    CneeId: 0,
    CneeUser: '',
    Phone: '',
    Address: '',
    IsDef: 0, //是否设置为默认
    newProvinceId: 0, //省ID所在下标
    newCityId: 0, //市ID所在下标
    newDistrictId: 0, //区ID所在下标
    textAddress: '',
    textDir: '请选择所在地区',
    showProvinces: [],
    showCitys: [],
    showDistricts: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

    common.pageInit(function() {});
    var that = this;
    var _from = options.from;
    var cneeId = options.CneeID;
    var _title = '添加收获地址';
    var text = '';
    that.setData({
      From: _from,
      CneeId: cneeId
    });

    if (cneeId > 0 && cneeId != null && cneeId != undefined) {
      _title = '修改收货地址';
    }
    wx.setNavigationBarTitle({
      title: _title
    }); //修改title
    //加载数据绑定
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    that.wxSubRequest('GET', appData.apiurl + '/mobile/api/Address/Edit', {
        custId: appData.custID,
        cneeId: cneeId
      },
      function(data) {
        if (data.code == 1200) {
          wx.hideLoading()
          if (data.content.Province != null) {
            text = data.content.Province;
          }
          if (data.content.City != null) {
            text = text + ' ' + data.content.City
          }
          if (data.content.District != null) {
            text = text + ' ' + data.content.District
          }
          that.setData({
            ObjAddress: data.content, //赋值对象
            CneeUser: data.content.CneeUser,
            Phone: data.content.Phone,
            Address: data.content.Address,
            textAddress: text,
            textDir: text.trim() == '' ? '请选择所在地区' : '',
            IsDef: data.content.IsDef
          })

          provinceId = data.content.ProvinceId;
          cityId = data.content.CityId;
          districtId = data.content.DistrictId;
          province = data.content.Province;
          city = data.content.City;
          district = data.content.District;
        }
        that.bindAreaData(provinceId, cityId, districtId); //加载省市区数据绑定
      },
      function(obj) {
        wx.hideLoading()
        console.log(obj)
      })

  },


  /**
   * 绑定区域设置表数据
   */
  bindAreaData: function(pID, cID, dID) {
    //获取省
    var that = this;
    var Plst = that.data.showProvinces;
    var Clst = that.data.showCitys;
    var Dlst = that.data.showDistricts;
    that.wxSubRequest('GET', appData.apiurl + 'mobile/api/Area/GetAreaByParentID', {
      parentID: 0
    }, function(res) {
      if (res.code == 1200) {
        for (var i = 0; i < res.content.length; i++) {
          Plst.push(res.content[i])
        }
      }
      if (pID != 0 && pID != null && pID != undefined) {
        for (var i = 0; i < Plst.length; i++) {
          if (pID == Plst[i].ID) {
            pID = i;
            break;
          }
        }
      }
      //重新赋值
      that.setData({
        showProvinces: Plst,
        newProvinceId: pID
      })
    })
    //获取市
    that.wxSubRequest('GET', appData.apiurl + 'mobile/api/Area/GetAreaByLevel', {
        level: 2
      },
      function(res) {
        if (res.code == 1200) {
          for (var i = 0; i < res.content.length; i++) {
            if (res.content[i].ParentID == Plst[that.data.newProvinceId].ID)
              Clst.push(res.content[i])

            citys.push(res.content[i]); //绑定全部市
          }
        }
        if (cID != 0 && cID != null && cID != undefined) {
          for (var i = 0; i < Clst.length; i++) {
            if (cID == Clst[i].ID) {
              cID = i;
              break;
            }
          }
        }
        //重新赋值
        that.setData({
          showCitys: Clst,
          newCityId: cID
        })
      })

    //获取区或县
    that.wxSubRequest('GET', appData.apiurl + 'mobile/api/Area/GetAreaByLevel', {
        level: 3
      },
      function(res) {
        if (res.code == 1200) {
          for (var i = 0; i < res.content.length; i++) {
            if (res.content[i].ParentID == Clst[that.data.newCityId].ID)
              Dlst.push(res.content[i])

            districts.push(res.content[i]); //绑定全部区或县
          }
        }
        if (dID != 0 && dID != null && dID != undefined) {
          for (var i = 0; i < Dlst.length; i++) {
            if (dID == Dlst[i].ID) {
              dID = i;
              break;
            }
          }
        }
        //重新赋值
        that.setData({
          showDistricts: Dlst,
          newDistrictId: dID
        })
      })
  },

  /**
   * 省市区选择器
   */
  bindMultiPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var that = this;
    provinceId = that.data.showProvinces[e.detail.value[0]].ID;
    province = that.data.showProvinces[e.detail.value[0]].AreaName;
    cityId = that.data.showCitys[e.detail.value[1]].ID;
    city = that.data.showCitys[e.detail.value[1]].AreaName;
    districtId = that.data.showDistricts[e.detail.value[2]].ID;
    district = that.data.showDistricts[e.detail.value[2]].AreaName;
    //重新赋值
    that.setData({
      newProvinceId: e.detail.value[0],
      newCityId: e.detail.value[1], //市ID
      newDistrictId: e.detail.value[2],
      textAddress: province + ' ' + city + ' ' + district,
      textDir: province == '' ? '请选择所在地区' : '',
    })

  },

  bindMultiPickerColumnChange: function(e) {
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    var that = this;
    var valId;
    var Dlen = [];
    switch (e.detail.column) {
      case 0:
        valId = that.data.showProvinces[e.detail.value].ID;
        var Clen = [];
        for (var i = 0; i < citys.length; i++) {
          if (citys[i].ParentID == valId) {
            Clen.push(citys[i])
          }
        }
        for (var j = 0; j < districts.length; j++) {
          if (districts[j].ParentID == Clen[0].ID) {
            Dlen.push(districts[j])
          }
        }
        that.setData({
          showCitys: Clen,
          showDistricts: Dlen
        })
        break;
      case 1:
        valId = that.data.showCitys[e.detail.value].ID;
        for (var k = 0; k < districts.length; k++) {
          if (districts[k].ParentID == valId) {
            Dlen.push(districts[k])
          }
        }
        that.setData({
          showDistricts: Dlen
        })
        break;
    }
  },

  /**
   * 输入收货人
   */
  bindCneeUserInput: function(event) {
    var that = this;
    that.setData({
      CneeUser: event.detail.value
    })
  },

  /**
   * 输入收货人手机号
   */
  bindPhoneInput: function(event) {
    var that = this;
    that.setData({
      Phone: event.detail.value
    })
  },

  /**
   * 输入详细地址
   */
  bindAddressInput: function(event) {
    var that = this;
    that.setData({
      Address: event.detail.value
    })
  },

  /**
   * 勾选默认地址
   */
  checkChangeTap: function(event) {
    var that = this;
    var val = event.detail.value.length;
    that.setData({
      IsDef: val
    })
  },

  /**
   * 提交保存地址
   */
  bindSaveTap: function(event) {
    var that = this;
    var pattern = /^1[34578]\d{9}$/;
    if (that.data.CneeUser == "" || that.data.CneeUser == null) {
      wx.showModal({
        title: '警告',
        content: '请输入收货人',
        showCancel: false
      })
      return;
    }
    if (that.data.Phone == "" || that.data.Phone == null) {
      wx.showModal({
        title: '警告',
        content: '请输入手机号码',
        showCancel: false
      })
      return;
    }
    if (!pattern.test(that.data.Phone)) {
      wx.showModal({
        title: '警告',
        content: '号码不对,请重新输入',
        showCancel: false
      })
      return;
    }
    if (provinceId == "-1" || provinceId == '') {
      wx.showModal({
        title: '警告',
        content: '请选择省份',
        showCancel: false
      })
    }
    if (cityId == "-1" || cityId == '') {
      wx.showModal({
        title: '警告',
        content: '请选择市',
        showCancel: false
      })
      return;
    }
    if (districtId == "-1" || districtId == '') {
      wx.showModal({
        title: '警告',
        content: '请选择区',
        showCancel: false
      })
      return;
    }
    if (that.data.Address == "" || that.data.Address == null) {
      wx.showModal({
        title: '警告',
        content: '请输入地址',
        showCancel: false
      })
      return;
    }
    var param = {
      CustID: appData.custID,
      UserID: wx.getStorageSync('UserInfo').UserID,
      CneeID: that.data.CneeId,
      CneeUser: that.data.CneeUser,
      Phone: that.data.Phone,
      ProvinceId: provinceId,
      Province: province,
      CityId: cityId,
      City: city,
      DistrictId: districtId,
      District: district,
      Address: that.data.Address,
      Status: 1,
      IsDef: that.data.IsDef
    };
    //加载数据绑定
    wx.showLoading({
      title: '保存中...',
      mask: true
    });
    that.wxSubRequest('POST', appData.apiurl + 'mobile/api/Address/DoEdit', param,
      function(data) {
        if (data.code == 1200) {
          wx.hideLoading()
          that.setData({
            CneeId: data.content.CneeID
          })
          var url = '/pages/deliveryAddr/deliveryAddr';
          if (that.data.From == 'order') {
            url = '/pages/submitOrder/submitOrder?CneeID=' + that.data.CneeId;
          } else if (that.data.From == 'team') {
            url = '/pages/teamSubmitOrder/teamSubmitOrder?CneeID=' + that.data.CneeId;
          }
          //跳转页面
          wx.redirectTo({
            url: url
          })
        }
      },
      function(obj) {
        wx.hideLoading()
        console.log(obj)
      })
  },


  /**
   * 微信提交请求获取数据或保存数据
   * 
   */
  wxSubRequest: function(method, url, param, callBack, CallBackError) {
    wx.request({
      url: url,
      method: method,
      data: param,
      header: {
        "content-type": "application/json",
        'X_ManuName': appData.manuName
      },
      success: function(res) {
        if (res.statusCode == 200 && res.data.code == 1200) {
          var data = res.data;
          callBack(data)
          console.log(res.data)
        }
      },
      fail: function(res) {
        CallBackError(res.data)
        console.log(res.data)
      },
      complete: function(res) {
        console.log(res.msg)
      }
    })
  },


  /********************************************************/

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})